import React from "react";
import { Page, Button, Input, Text } from "zmp-ui";
import { useI18n } from "../i18n";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useRecoilState, useSetRecoilState, useRecoilValue } from "recoil";
import { selectedCountryCodeState, loginPageState, authTokenState, currentUserState, userCenterDataState, userCenterDataLoadingState, fetchUserCenterData } from "../state";
import { authApi } from "../api/login";

const Login: React.FunctionComponent = () => {
  const { t } = useI18n();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [countryCode, setCountryCode] = useRecoilState(selectedCountryCodeState);
  const [loginState, setLoginState] = useRecoilState(loginPageState);
  const setAuthToken = useSetRecoilState(authTokenState);
  const setCurrentUser = useSetRecoilState(currentUserState);
  const setUserCenterData = useSetRecoilState(userCenterDataState);
  const setUserCenterDataLoading = useSetRecoilState(userCenterDataLoadingState);
  const authToken = useRecoilValue(authTokenState);
  
  // 页面状态管理 - 使用Recoil状态
  const { pageType, loginType, agree } = loginState;
  const [showPopover, setShowPopover] = React.useState(false);
  
  // 更新页面状态的辅助函数
  const updateLoginState = (updates: Partial<typeof loginState>) => {
    setLoginState(prev => ({ ...prev, ...updates }));
  };
  
  // 表单数据
  const [phone, setPhone] = React.useState('');
  // const [email, setEmail] = React.useState(''); // 暂时注释邮箱相关
  const [otpPhone, setOtpPhone] = React.useState('');
  // const [otpEmail, setOtpEmail] = React.useState(''); // 暂时注释邮箱相关

  // 检查是否已经登录，如果已登录则直接跳转到首页
  React.useEffect(() => {
    if (authToken) {
      console.log('登录页面：检测到已登录用户，跳转到首页');
      navigate('/home', { replace: true });
      return;
    }
  }, [authToken, navigate]);

  // 从URL参数获取状态（兼容性处理）
  React.useEffect(() => {
    const urlPageType = searchParams.get('pageType');
    const urlLoginType = searchParams.get('loginType');
    
    if (urlPageType || urlLoginType) {
      updateLoginState({
        pageType: urlPageType ? parseInt(urlPageType) as 1 | 2 | 3 : pageType,
        loginType: urlLoginType ? parseInt(urlLoginType) as 0 | 6 : loginType
      });
    }
  }, [searchParams]);
  
  // 倒计时状态
  const [countPhone, setCountPhone] = React.useState<number>(-1);
  // const [countEmail, setCountEmail] = React.useState<number>(-1); // 暂时注释邮箱相关
  
  // 加载和错误状态
  const [isLoading, setIsLoading] = React.useState(false);
  const [error, setError] = React.useState<string>('');

  // 倒计时逻辑
  React.useEffect(() => {
    if (countPhone > -1) {
      const id = setTimeout(() => setCountPhone((s) => (s > 0 ? s - 1 : -1)), 1000);
      return () => clearTimeout(id);
    }
    return undefined;
  }, [countPhone]);
  
  // 邮箱倒计时逻辑 - 暂时注释
  // React.useEffect(() => {
  //   if (countEmail > -1) {
  //     const id = setTimeout(() => setCountEmail((s) => (s > 0 ? s - 1 : -1)), 1000);
  //     return () => clearTimeout(id);
  //   }
  // }, [countEmail]);

  // 协议检查
  const guardAgree = (next: () => void) => {
    if (!agree) {
      setShowPopover(true);
      setTimeout(() => setShowPopover(false), 3000);
      return;
    }
    next();
  };

  // 选择登录方式 - 现在只有手机号登录
  const loginBtn = () => {
    guardAgree(() => {
      updateLoginState({
        loginType: 0, // 固定为手机号登录
        pageType: 3
      });
    });
  };

  // 发送验证码
  const sendOtpPhone = async () => {
    if (!countryCode || !phone || phone.length < 8) return;
    
    setIsLoading(true);
    setError('');
    
    try {
      await authApi.sendMobileLoginCode({ 
        countryCode: countryCode, 
        phoneNumber: phone, 
        type: 'login' 
      });
      setCountPhone(59);
    } catch (err: any) {
      console.error('发送验证码错误:', err);
      setError(err.message || '发送验证码失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 邮箱发送验证码 - 暂时注释
  // const sendOtpEmail = () => {
  //   if (!email || !email.includes('@')) return;
  //   setCountEmail(59);
  // };

  // 提交登录
  const submitForm = async () => {
    if (loginType === 0) {
      if (!phone || !otpPhone) return;
      
      setIsLoading(true);
      setError('');
      
      try {
        const result = await authApi.mobileLogin({ 
          countryCode: countryCode, 
          phoneNumber: phone, 
          securityCode: otpPhone 
        });
        
        // 登录成功，保存token和用户信息
        console.log('登录成功:', result);
        
        // 保存token到状态管理和localStorage (userId就是token)
        if (result?.data?.userId) {
          const token = String(result.data.userId);
          setAuthToken(token);
          setCurrentUser(result.data);
          // 同时保存到localStorage，供HTTP客户端自动获取
          localStorage.setItem('authToken', token);
          
          // 登录成功后获取用户中心数据
          await fetchUserCenterData(setUserCenterData, setUserCenterDataLoading);
        }
        
        // 跳转到首页，替换当前页面（避免返回登录页）
        navigate('/home', { replace: true });
        
      } catch (err: any) {
        console.error('登录错误:', err);
        setError(err.message || '登录失败');
      } finally {
        setIsLoading(false);
      }
    }
    // 邮箱登录逻辑 - 暂时注释
    // else {
    //   if (!email || !otpEmail) return;
    //   // 邮箱登录逻辑
    //   console.log('邮箱登录:', { email, otpEmail });
    // }
  };

  return (
    <Page className="page" style={{ background: '#fff' }}>
      <div style={{ 
        width: '100%', 
        minHeight: '100vh', 
        display: 'flex', 
        flexDirection: 'column',
        padding: pageType === 1 ? '44px 16px' : '0 16px'
      }}>
        
        {/* 页面1: 登录方式选择 */}
        {pageType === 1 && (
          <>
            {/* Logo */}
            <div style={{ textAlign: 'center', marginBottom: 32 }}>
              <img 
                src="/src/assets/img/login/logo.png" 
                alt="Logo" 
                style={{ width: 88, height: 88 }}
              />
            </div>
            
            {/* 标题 */}
            <div style={{ 
              textAlign: 'center', 
              fontSize: 28, 
              fontWeight: 'bold', 
              color: '#39404d',
              lineHeight: '34px',
              marginBottom: 48
            }}>
              {t('login.welcomeTitle')}
            </div>

            {/* 登录方式选择 */}
            <div>
              {/* 手机号登录 */}
              <div
                onClick={loginBtn}
                style={{ 
                  width: '100%',
                  height: 52, 
                  background: '#f7f7f9', 
                  borderRadius: 5, 
                  display: 'flex', 
                  alignItems: 'center',
                  position: 'relative',
                  cursor: 'pointer',
                  marginBottom: 14
                }}
              >
                <img 
                  src="/src/assets/img/login/phone@2x.png" 
                  alt="Phone" 
                  style={{ width: 32, height: 32, marginLeft: 56 }}
                />
                <span style={{ 
                  fontSize: 17, 
                  fontWeight: 400, 
                  color: '#39404d', 
                  marginLeft: 16,
                  lineHeight: '24px',
                  letterSpacing: '0.32px'
                }}>
                  {t('login.withPhone')}
                </span>
              </div>

              {/* 邮箱登录 - 暂时注释 */}
              {/* <div
                onClick={() => loginBtn(6)}
                style={{ 
                  width: '100%',
                  height: 52, 
                  background: '#f7f7f9', 
                  borderRadius: 5, 
                  display: 'flex', 
                  alignItems: 'center',
                  position: 'relative',
                  cursor: 'pointer'
                }}
              >
                <img 
                  src="/src/assets/img/login/ic_email@2x.png" 
                  alt="Email" 
                  style={{ width: 32, height: 32, marginLeft: 56 }}
                />
                <span style={{ 
                  fontSize: 17, 
                  fontWeight: 400, 
                  color: '#39404d', 
                  marginLeft: 16,
                  lineHeight: '24px',
                  letterSpacing: '0.32px'
                }}>
                  {t('login.withEmail')}
                </span>
              </div> */}
            </div>

            {/* 协议同意 */}
            <div style={{ 
              display: 'flex', 
              alignItems: 'flex-start', 
              marginTop: 20,
              fontSize: 12,
              fontWeight: 500,
              color: '#39404d',
              lineHeight: '24px'
            }}>
              <div style={{ position: 'relative' }}>
                <img
                  src={agree ? "/src/assets/img/login/login_ic_check_selected.svg" : "/src/assets/img/login/login_ic_check_unselected.svg"}
                  alt=""
                  style={{ width: 14, height: 14, margin: '5px 6px 0 0' }}
                  onClick={() => updateLoginState({ agree: !agree })}
                />
                {showPopover && (
                  <div style={{
                    position: 'absolute',
                    top: -40,
                    left: 0,
                    background: '#aaaaac',
                    borderRadius: 8,
                    padding: '10px 16px',
                    fontSize: 12,
                    fontWeight: 500,
                    color: '#ffffff',
                    lineHeight: '14px',
                    whiteSpace: 'nowrap',
                    zIndex: 1000
                  }}>
                    {t('login.agreeWarning')}
                  </div>
                )}
              </div>
              <span onClick={() => updateLoginState({ agree: !agree })} style={{ cursor: 'pointer' }}>
                {t('login.agreeText')}
              </span>
            </div>
          </>
        )}

        {/* 页面3: 输入验证码 */}
        {pageType === 3 && (
          <>
            {/* 返回按钮 */}
            <div style={{ 
              display: 'flex', 
              alignItems: 'center', 
              height: 44,
              marginBottom: 28
            }}>
              <button 
                onClick={() => updateLoginState({ pageType: 1 })} 
                style={{ 
                  background: 'none', 
                  border: 0, 
                  padding: '0 12px',
                  fontSize: 18,
                  color: '#39404d'
                }}
              >
                ←
              </button>
            </div>

            {/* 标题 */}
            <div style={{ 
              fontSize: 28, 
              fontWeight: 'bold', 
              color: '#39404d',
              lineHeight: '34px',
              marginBottom: 28
            }}>
              {t('login.withPhone')}
            </div>

            {/* 错误提示 */}
            {error && (
              <div style={{
                marginTop: 20,
                padding: '12px 16px',
                background: '#ffebee',
                borderRadius: 8,
                color: '#c62828',
                fontSize: 14,
                textAlign: 'center'
              }}>
                {error}
              </div>
            )}

            {/* 表单 */}
            <div style={{ marginTop: 28 }}>
              {/* 手机号输入 */}
              <div style={{ 
                position: 'relative',
                marginBottom: 20
              }}>
                <div 
                  onClick={() => navigate('/country-code')}
                  style={{
                    position: 'absolute',
                    left: 28,
                    top: '50%',
                    transform: 'translateY(-50%)',
                    zIndex: 6,
                    color: '#39404d',
                    fontSize: 14,
                    fontWeight: 600,
                    lineHeight: '54px',
                    cursor: 'pointer'
                  }}
                >
                  +{countryCode}
                  <span style={{ marginLeft: 10, fontSize: 12 }}>▼</span>
                </div>
                <Input
                  type="text"
                  maxLength={15}
                  placeholder={t('login.phonePlaceholder')}
                  value={phone}
                  onChange={(e) => setPhone(String(e.target.value).replace(/[^\d]/g, ''))}
                  style={{
                    height: 52,
                    background: '#f0f0f2',
                    borderRadius: 14,
                    border: 'none',
                    paddingLeft: '120px',
                    fontSize: 14,
                    fontWeight: 600,
                    color: '#39404d',
                    lineHeight: '16px'
                  }}
                />
              </div>

              <div style={{ 
                position: 'relative',
                marginBottom: 20
              }}>
                <div
                  onClick={countPhone > -1 || isLoading ? undefined : sendOtpPhone}
                  style={{
                    position: 'absolute',
                    right: 8,
                    top: 8,
                    height: 36,
                    background: (countPhone > -1 || isLoading) ? '#cecece' : '#000000',
                    borderRadius: 6,
                    padding: '0 8px',
                    color: '#ffffff',
                    fontSize: 12,
                    fontWeight: 500,
                    lineHeight: '36px',
                    minWidth: 88,
                    textAlign: 'center',
                    cursor: (countPhone > -1 || isLoading) ? 'not-allowed' : 'pointer',
                    zIndex: 6,
                    transition: 'all 0.2s ease-in-out'
                  }}
                >
                  {isLoading ? '发送中...' : (countPhone > -1 ? `${countPhone}s` : t('login.getCode'))}
                </div>
                <Input
                  type="text"
                  maxLength={6}
                  placeholder={t('login.codePlaceholder')}
                  value={otpPhone}
                  onChange={(e) => setOtpPhone(String(e.target.value).replace(/[^\d]/g, ''))}
                  style={{
                    height: 52,
                    background: '#f0f0f2',
                    borderRadius: 14,
                    border: 'none',
                    paddingRight: '100px',
                    paddingLeft: 28,
                    fontSize: 14,
                    fontWeight: 600,
                    color: '#39404d',
                    lineHeight: '16px'
                  }}
                />
              </div>

              {/* 邮箱输入 */}
              {/* {loginType === 6 && (
                <>
                  <div style={{ marginBottom: 20 }}>
                    <Input
                      type="text"
                      maxLength={320}
                      placeholder={t('login.emailPlaceholder')}
                      value={email}
                      onChange={(v) => setEmail(String(v))}
                      style={{
                        height: 52,
                        background: '#f0f0f2',
                        borderRadius: 14,
                        border: 'none',
                        paddingLeft: 28,
                        fontSize: 14,
                        fontWeight: 600,
                        color: '#39404d',
                        lineHeight: '16px'
                      }}
                    />
                  </div>

                  <div style={{ 
                    position: 'relative',
                    marginBottom: 20
                  }}>
                    <div
                      onClick={countEmail > -1 ? undefined : sendOtpEmail}
                      style={{
                        position: 'absolute',
                        right: 8,
                        top: 8,
                        height: 36,
                        background: countEmail > -1 ? '#cecece' : '#000000',
                        borderRadius: 6,
                        padding: '0 8px',
                        color: '#ffffff',
                        fontSize: 12,
                        fontWeight: 500,
                        lineHeight: '36px',
                        minWidth: 88,
                        textAlign: 'center',
                        cursor: countEmail > -1 ? 'not-allowed' : 'pointer',
                        zIndex: 6,
                        transition: 'all 0.2s ease-in-out'
                      }}
                    >
                      {countEmail > -1 ? `${countEmail}s` : t('login.getCode')}
                    </div>
                    <Input
                      type="text"
                      maxLength={4}
                      placeholder={t('login.codePlaceholder')}
                      value={otpEmail}
                      onChange={(v) => setOtpEmail(String(v).replace(/[^\d]/g, ''))}
                      style={{
                        height: 52,
                        background: '#f0f0f2',
                        borderRadius: 14,
                        border: 'none',
                        paddingRight: '100px',
                        paddingLeft: 28,
                        fontSize: 14,
                        fontWeight: 600,
                        color: '#39404d',
                        lineHeight: '16px'
                      }}
                    />
                  </div>
                </>
              )} */}

              {/* 登录按钮 */}
              <button
                onClick={submitForm}
                disabled={isLoading}
                style={{
                  width: '100%',
                  height: 52,
                  background: isLoading ? '#cecece' : '#000000',
                  border: 'none',
                  borderRadius: 14,
                  fontSize: 17,
                  fontWeight: 500,
                  lineHeight: '20px',
                  color: '#ffffff',
                  marginTop: 68,
                  cursor: isLoading ? 'not-allowed' : 'pointer',
                  transition: 'all 0.2s ease-in-out',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
                onMouseDown={(e) => {
                  if (!isLoading) {
                    e.currentTarget.style.background = '#4c4a4c';
                  }
                }}
                onMouseUp={(e) => {
                  if (!isLoading) {
                    e.currentTarget.style.background = '#000000';
                  }
                }}
                onMouseLeave={(e) => {
                  if (!isLoading) {
                    e.currentTarget.style.background = '#000000';
                  }
                }}
              >
                {isLoading ? '登录中...' : t('login.submit')}
              </button>
            </div>
          </>
        )}
      </div>
    </Page>
  );
};

export default Login;